package com.example.interceptor;

import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Description:1.定义拦截器
 * User: 阿宾
 * Date: 2025-05-16
 * Time: 09:24
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //1.从header中获取token，注意要和前端中设置的名称一样
        String jwtToken = request.getHeader("user_token_header");
        log.info("从header中获取token：{}",jwtToken);
        //2.校验用户token
        Claims claims = JwtUtils.parseJWT(jwtToken);
        if(claims == null){
            log.info("用户token：{}",claims);
            //设置状态码为401表示校验失败
            response.setStatus(401);
            return false; //进行拦截
        }
        log.info("令牌校验通过，放行");
        return true;//进行放行
    }
}
